﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProjectStorageLib.ParameterizedNomencaltures;
using System.IO;
using StorageProject.DocumentGenerator.CSV;

public partial class controls_ProjectsExportList : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void m_lbSPSExport_Click(object sender, EventArgs e)
    {
        using (NomenclatureRetriever ret = new NomenclatureRetriever())
        {
            var objects = ret.GetAll();

            StorageProject.DocumentGenerator.Transformations.Transformer r =
                new StorageProject.DocumentGenerator.Transformations.Transformer();

            var res = r.Transform(ProjectStorage.DocumentGenerator.Common.SPSFILENAME, objects);

            fileToResponse(res, "data.sps");
        }
    }

    protected void m_lbData_Click(object sender, EventArgs e)
    {
        generateDataFile();
    }

   protected void  m_lbSCVExport_Click(object sender, EventArgs e)
    {
        generateCSVFile();
    }

    public void fileToResponse(TextReader reader, string fileName)
    {
        Response.Clear();

        Response.AddHeader("Content-disposition", string.Format( "attachment; filename={0}", fileName));
        Response.ContentType = "application/octet-stream";

        copyStream(reader, Response.Output);
        Response.End();
    }

    public static void copyStream(TextReader input, TextWriter output)
    {
        char[] buffer = new char[32768];
        while (true)
        {
            //int read = input.Read(buffer, 0, buffer.Length);
            //if (read <= 0)
            //    return;
            //output.Write(buffer, 0, read);
            var a = input.ReadLine();
            if (a == null)
                break;
            output.WriteLine(a);
        }
    }

    public delegate List<ProjectStorageLib.Project.ProjectManager> GetData();
    public event GetData GetDataEvent = null;

    protected void generateDataFile()
    {
        if (GetDataEvent != null)
        {
            var data = GetDataEvent.Invoke();

            var transformer = new ProjectStorage.DocumentGenerator.CodeTransformations.CommaSeparetedProjectList(data);

            var stream = new StringReader(transformer.Generate());

            fileToResponse(stream, "data.dat");
        }
    }
    protected void generateCSVFile()
    {
        if (GetDataEvent != null)
        {
            var data = GetDataEvent.Invoke();

            if (data == null)
                return;

            var transformer  = new CSSTemplate();

            var stream = new StringReader(transformer.Export(data));

            fileToResponse(stream, "data.csv");
        }
    }


}